import { useEffect, useRef, useState } from 'react';
import './index.css';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend, getEmptyImage } from 'react-dnd-html5-backend';
import DragLayer from './DragLayer';

interface ItemType {
    color: string;
}
interface BoxProps {
    color: string
}
function Box(props: BoxProps) {
    const ref = useRef(null);

    const [{ dragging }, drag, dragPreview] = useDrag({
        type: 'box',
        item: {
            color: props.color
        },
        collect(monitor) {
            return {
                dragging: monitor.isDragging()
            }
        }
    });

    useEffect(() => {
        drag(ref);
        dragPreview(getEmptyImage(), { captureDraggingState: true });
    }, [])

    return <div ref={ref} className={dragging ? 'box dragging' : 'box'} style={
        { background: props.color || 'blue' }
    }></div>
}


function Container() {
    const [boxes, setBoxes] = useState<ItemType[]>([]);
    const ref = useRef(null);

    const [, drop] = useDrop(() => {
        return {
            accept: 'box',
            drop(item: ItemType) {
                setBoxes((boxes) => [...boxes, item])
            }
        }
    });

    useEffect(()=> {
        drop(ref);
    }, []);
    
    return <div ref={ref} className="container">
        {
            boxes.map(item => {
                return <Box color={item.color}></Box>
            })
        }
    </div>
}

function InnerTestReactDnD() {
    return <div>
        <Container></Container>
        <Box color='blue'></Box>
        <Box color='red'></Box>
        <Box color='green'></Box>
        <DragLayer />
    </div>
}

const TestReactDnD = () => {
    return <DndProvider backend={HTML5Backend}>
        <InnerTestReactDnD />
    </DndProvider>
}

export default TestReactDnD;
